package cn.fx.basic.util;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.nio.charset.StandardCharsets;

/**
 * 短信发送工具类
 */
public class SmsSendUtil {

    //用户名
    private static  final String UID = "啊祥512";
    //秘钥
    private static  final String KEY = "7481575C5BF4CDED2766BDE96396BEA1";

    public static String smsSend(String phone,String code){
        try {
            //发送http请求
            HttpClient client = new HttpClient();
            //发送接口路径
            PostMethod post = new PostMethod("https://utf8api.smschinese.cn/");
            //在头文件中设置转码
            post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
            NameValuePair[] data ={
                    new NameValuePair("Uid", UID),
                    new NameValuePair("Key", KEY),
                    new NameValuePair("smsMob",phone),
                    new NameValuePair("smsText",code)};
            post.setRequestBody(data);

            client.executeMethod(post);
            Header[] headers = post.getResponseHeaders();
            int statusCode = post.getStatusCode();
            System.out.println("statusCode:"+statusCode); //HTTP状态码
            for(Header h : headers){
                System.out.println(h.toString());
            }
            String result = new String(post.getResponseBodyAsString().getBytes(StandardCharsets.UTF_8));
            System.out.println(result);  //打印返回消息状态

            post.releaseConnection();
            return code;
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        smsSend("15281003975","短信验证码为:8846");
    }
}